package gitee.derumin.really_forge.mixin;

import gitee.derumin.really_forge.block_entities.AnvilBlockEntity;
import net.minecraft.block.AnvilBlock;
import net.minecraft.block.BlockEntityProvider;
import net.minecraft.block.BlockState;
import net.minecraft.block.FallingBlock;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;

@Mixin(AnvilBlock.class)
public abstract class AnvilBlockMixin extends FallingBlock implements BlockEntityProvider {

    public AnvilBlockMixin(Settings settings) {
        super(settings);
    }

    /**
     * @author derumin
     * @reason no reason
     */
    @Overwrite
    public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
        AnvilBlockEntity anvil = (AnvilBlockEntity) world.getBlockEntity(pos);
        if (anvil == null){
            return ActionResult.PASS;
        }
        return anvil.interactWith(player, hand, world);
    }

    @Override
    public void onStateReplaced(BlockState state, World world, BlockPos pos, BlockState newState, boolean moved) {
        if (!state.isOf(newState.getBlock())) {
            BlockEntity blockEntity = world.getBlockEntity(pos);
            if (blockEntity instanceof AnvilBlockEntity anvil) {
                anvil.dropItems(1);
                world.updateComparators(pos, this);
            }
            super.onStateReplaced(state, world, pos, newState, moved);
        }
    }

    @Override
    public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {
        return new AnvilBlockEntity(pos, state);
    }
}
